<?php

class EventCustomerController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			/*array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('admin'),
			),*/
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','view','lottery'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'actions'=>array('index'),
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new EventCustomer;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$event_code = $_GET['event_code'];
		$provide_gift_number = $_POST['provide_gift_number'];
		$lottery_numbers = $_POST['lottery_numbers'];
		$user_id = Yii :: app()->user->id;
		$event_id=$_POST['event_id'];
		if (isset ($_POST['EventCustomer'])) {
			$model->attributes = $_POST['EventCustomer'];
			if (empty ($lottery_numbers)) {
				$this->redirect(array (
					'create',
					'errorId' => 1
				)); //1:为抽奖数为空的时候返回页面提示
			}
			//获取电话
			$moble = EventCustomer :: model()->getGiftNumber($model->event_code, $user_id);
			if (!empty ($moble)) {
				for ($j = 0; $j < count($moble); $j++) {
					$mobles[$j] = $moble[$j]['mobile']; //把数组转换成arra('0'=>1212)格式
				}
				$result = array_rand($mobles, $lottery_numbers > count($mobles) ? count($mobles) : $lottery_numbers); //随机取出数组中的键值,如果只取出一个,返回的是一个随机的键值数.
				if (count($result) > 1) { //array_rand 函数只有一个值的时候,不是数组
					array_unique($result); //去除数组中重复的键值
				}
				for ($i = 0; $i < count($result); $i++) {
					//如果 count($result) 等于 1 , $result的结果就是一个随机键值,是整数,所以不能循环
					if (count($result) == 1) {
						$unms = $result;
					} else {
						$unms = $result[$i];
					}
					//把取出值的记录标记为已中奖
					$rs = EventCustomer :: model()->setLotteryUserStatus($mobles[$unms], $user_id,$event_code);
					$customer_id = EventCustomer :: model()->getCuid($mobles[$unms], $user_id);
					$models = EventCustomer :: model()->findByPk($customer_id);
					//获取密码
					$password_model = EventCustomer :: model()->getPassword($event_code,$user_id);
					//获取邮件模板
					$emailtemplate=EventCustomer::model()->getEmail($event_id,$model);
					//获取短信模板
					$smstemplate=EventCustomer::model()->getSms($event_id,$model);
					$text=str_replace ( "{lastName}", $models['lastname'], $smstemplate );
					$text=str_replace ( "{firstName}", $models['firstname'], $text );
					$text=str_replace ( "{awardCode}", $password_model['password'], $text );
					$text=str_replace ( "{awardAddress}", $models['award_address'], $text );
					//发送EMAIL.
					EventCustomer :: model()->sendEmail($models->emailaddress, $models->firstname,$models->lastname,$password_model['password'],$models['award_address'],$models->lang,$emailtemplate);
					//根据当前系统的语言发送给用户是否中文还是英文
					$post_data = array (
						'method' => "sendMessages",
						'username' => "abc",
						'password' => "123456",
						'mobile' => $mobles[$unms],
						'api_id' => 53,
						'text' => $text//'Congratulations, you won NetCube 3G wireless Internet Activities Awards! Please check to see how to collect their prizes registered mail.'
					);
					/*}*/
					$url = "http://sms.webnova.com.au/api/webnova_sms_api_lib.php";
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
					curl_setopt($ch, CURLOPT_POST, 1);
					// 把post的变量加上
					curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
					$output = curl_exec($ch);
					//调试使用
					if ($output === FALSE) {
						$output = "cURL Error: " . curl_error($ch);
					}else{
						EventCustomer :: model()->setSmsUserStatus($models->mobile, $user_id);
						EventCustomer :: model()->setPasswordState($password_model['gift_password_id']);
						//把调查用户ID反填到密码suser_id字段中
						EventCustomer :: model()->setSuserId($password_model['gift_password_id'],$customer_id);
					}
					curl_close($ch);
					//短信发送结束----------------------------------------
				}
				if ($i)
					$this->redirect(array (
						'admin',
						'id' => $model->customer_id
					));
				} else {
				$this->redirect(array (
					'create',
					'errorId' => 2
				));
			}
		}
		$this->render('create', array (
			'model' => $model,

			
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['EventCustomer']))
		{
			$model->attributes=$_POST['EventCustomer'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->customer_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('EventCustomer');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new EventCustomer('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['EventCustomer']))
			$model->attributes=$_GET['EventCustomer'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return EventCustomer the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=EventCustomer::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param EventCustomer $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='event-customer-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	
	public function actionLottery() {
		$model = new EventCustomer('search');
		$model->unsetAttributes(); // clear any default values
		if (isset ($_GET['EventCustomer'])) {
			$model->attributes = $_GET['EventCustomer'];
		}
		$model->partner_id = $_GET['user_id'];
		$model->event_code = $_GET['event_code'];
		$model->winning_status = 0;
		$this->render('_formLottery', array (
			'model' => $model,
		));

	}
	
	
	//根据code获取此活动中的设置礼品数
	public function actionGiftNumber() {
		$event_code = isset ($_GET['code']) ? $_GET['code'] : 0;
		$user_id = Yii :: app()->user->id;
		$sql = "select * from zy_event where user_id='" . $user_id . "' and event_code='" . $event_code . "'";
		$rs = Yii :: app()->db->createCommand($sql)->queryAll();
		echo $rs[0]['prize_qty'];
	}
	
	
		//手动抽奖
		public function actionConfirmPrizeWinning() {
			$userId = Yii :: app()->user->id;
			$event_code = $_POST['code'];
			$event_id=$_POST['event_id'];
			if (Yii :: app()->request->isPostRequest) {
			$model = new EventCustomer();
			$customer_id_list = $_POST['customer_id'];
			for ($i = 0; $i < count($customer_id_list); $i++) {	
				//获取最后一步的步数
				//$stepnum=EventCustomer::model()->getEndStep($event_id);			
				//查询用户资料
				$model = EventCustomer :: model()->findByPk($customer_id_list[$i]);	
				//把取出值的记录标记为已中奖
				$rs = EventCustomer :: model()->setLotteryUserStatus($model->mobile, $userId,$event_code);						
				$customer_id = $model->customer_id;
				//获取密码
				$password_model = EventCustomer :: model()->getPassword($event_code,$userId);
				//获取地址
				//$award_model=AwardAddress :: model()->findByPk($model->award_address_id);
				//获取邮件模板
				$emailtemplate=EventCustomer::model()->getEmail($event_id,$model);
				//获取短信模板
				$smstemplate=EventCustomer::model()->getSms($event_id,$model);			
				$text=str_replace ( "{lastName}", $model['lastname'], $smstemplate );
				$text=str_replace ( "{firstName}", $model['firstname'], $text );
				$text=str_replace ( "{awardCode}", $password_model['password'], $text );
				$text=str_replace ( "{awardAddress}", $model['award_address'], $text );
				//发送EMAIL.
				EventCustomer :: model()->sendEmail($model->emailaddress, $model->firstname,$model->lastname,$password_model['password'],$model['award_address'],$model->lang,$emailtemplate);
			
				$post_data = array (
					'method' => "sendMessages",
					'username' => "abc",
					'password' => "123456",
					'mobile' => $model->mobile,
					'api_id' => 53,
					'text' => $text
				);
				/*}*/
				$url = "http://sms.webnova.com.au/api/webnova_sms_api_lib.php";
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
				curl_setopt($ch, CURLOPT_POST, 1);
				// 把post的变量加上
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
				$output = curl_exec($ch);
				//调试使用
				if ($output === FALSE) {
					$output = "cURL Error: " . curl_error($ch);
				} else {
					EventCustomer :: model()->setSmsUserStatus($model->mobile, $userId);
					EventCustomer :: model()->setPasswordState($password_model['gift_password_id']);
					//把调查用户ID反填到密码suser_id字段中
					EventCustomer :: model()->setSuserId($password_model['gift_password_id'],$customer_id);
				}
				curl_close($ch);
				//短信发送结束----------------------------------------
			}
			if (isset (Yii :: app()->request->isAjaxRequest)) {
				echo 'ok,' . $event_code;
			} else {
				$this->redirect(array (
					'EventCustomer/lottery',
					'user_id' => $userId,
					'event_code' => $event_code,
					'errorId' => 1
				)); 
			}
		} else
			throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
	}
	
	/**
	 * 跟据活动导出调查用户
	 */
	public function actionExport(){
		$eventCode = $_GET['event_code'];
		EventCustomer::model()->getSurveyUser($eventCode);
	}
	
	
	//发送领奖密码
	public function actionSendSms()
	{
		$customerid = Yii::app ()->request->getparam ( 'customerid' );
		$event_id = Yii::app ()->request->getparam ( 'event_id' );
		$model = EventCustomer :: model()->findByPk($customerid);
		$model1=EventGiftPassword::model()->findByAttributes(array('partner_id'=>$customerid));
		//$award_model=AwardAddress :: model()->findByPk($model->award_address_id);
		//获取短信模板
		$smstemplate=EventCustomer::model()->getSms($event_id,$model);
				$text=str_replace ( "{lastName}", $model['lastname'], $smstemplate );
				$text=str_replace ( "{firstName}", $model['firstname'], $text );
				$text=str_replace ( "{awardCode}", $model1['password'], $text );
				$text=str_replace ( "{awardAddress}", $model['award_address'], $text );
		$post_data = array (
				'method' => "sendMessages",
				'username' => "abc",
				'password' => "123456",
				'mobile' => $model->mobile,
				'api_id' => 53,
				'text' => $text
		);
		print_r ( $post_data );
		/* } */
		$url ="http://sms.webnova.com.au/api/webnova_sms_api_lib.php";
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 0 );
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		// 把post的变量加上
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
		$output = curl_exec ( $ch );
		// 调试使用
		curl_close ( $ch );
		if ($output === FALSE) {
			$output = "cURL Error: " . curl_error ( $ch );
		} else {
			EventCustomer::model ()->setSmsUserStatus ($model->mobile, $model->partner_id );
		if (isset ( Yii::app ()->request->isAjaxRequest )) {
				echo 'ok,' .$model->event_code;
			} else {
				$this->redirect ( array (
						'eventCustomer/admin',
					'event_code' =>$model->event_code,
						'errorId' => 1
				) );
			}
		}		
		// 短信发送结束----------------------------------------
	}
	
	
	// 发送中奖通知
	public function ActionSendInform() {
		$customerid = Yii::app ()->request->getparam ( 'customerid' );
		$event_id = Yii::app ()->request->getparam ( 'event_id' );
		$model = EventCustomer :: model()->findByPk($customerid);
		$model1=EventGiftPassword::model()->findByAttributes(array('partner_id'=>$customerid));
		//$award_model=AwardAddress :: model()->findByPk($model->award_address_id);
		//获取邮件模板
		$emailtemplate=EventCustomer::model()->getEmail($event_id,$model);
		//获取短信模板
		$smstemplate=EventCustomer::model()->getSms($event_id,$model);
				$text=str_replace ( "{lastName}", $model['lastname'], $smstemplate );
				$text=str_replace ( "{firstName}", $model['firstname'], $text );
				$text=str_replace ( "{awardCode}", $model1['password'], $text );
				$text=str_replace ( "{awardAddress}", $model['award_address'], $text );
		// 发送EMAIL.
		EventCustomer :: model()->sendEmail($model->emailaddress, $model->firstname,$model->lastname,$password_model->password,$model->award_address,$model->lang,$emailtemplate);
		$post_data = array (
				'method' => "sendMessages",
				'username' => "abc",
				'password' => "123456",
				'mobile' => $model->mobile,
				'api_id' => 53,
				'text' => $text
		);
		print_r ( $post_data );
		/* } */
		$url ="http://sms.webnova.com.au/api/webnova_sms_api_lib.php";
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 0 );
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		// 把post的变量加上
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
		$output = curl_exec ( $ch );
		// 调试使用
		if ($output === FALSE) {
			$output = "cURL Error: " . curl_error ( $ch );
		} else {
			EventCustomer::model ()->setSmsUserStatus ($model->mobile, $model->partner_id );
		if (isset ( Yii::app ()->request->isAjaxRequest )) {
				echo 'ok,' .$model->event_code;
			} else {
				$this->redirect ( array (
						'eventCustomer/admin',
						'event_code' =>$model->event_code,
						'errorId' => 1
				) );
			}
		}
		curl_close ( $ch );
		// 短信发送结束----------------------------------------
		}
	}
